package com.base.core.aspect;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.ArrayList;

import com.base.core.interceptor.ServiceInterceptor;


public class ServiceFactory implements InvocationHandler {

	private static ArrayList<ServiceInterceptor> interceptors;
	
	public ArrayList<ServiceInterceptor> getInterceptors() {
		return interceptors;
	}

	public void setInterceptors(ArrayList<ServiceInterceptor> interceptors) {
		this.interceptors = interceptors;
	}

	private Object delegate;

	public Object bind(Object delegate) {
		this.delegate = delegate;
		return Proxy.newProxyInstance(delegate.getClass().getClassLoader(),
				delegate.getClass().getInterfaces(), this);
	}

	@Override
	public Object invoke(Object proxy, Method method, Object[] args) {
		Object result = null;
		try {
			for(ServiceInterceptor interceptor:interceptors){
				interceptor.before();
			}
			result = method.invoke(delegate, args);
			for(ServiceInterceptor interceptor:interceptors){
				interceptor.after();
			}
		} catch (Exception e) {

		}
		return result;
	}

}
